/*
 * @Author: 橘子
 * @Date: 2023-03-10 16:06
 * @Project_description: 过滤路由
 * @Description: 代码是我抄的，不会也是真的
 */

'use strict'
import layoutHeaderAside from '@/layout/header-aside'
import router from '@/router'
import { cloneDeep } from 'lodash'

/**
 * 路由懒加载
 * @param view  路由
 * @returns {(function(*): any)|(function(): Promise<*>)}
 */
export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views${view}`)
  }
}

//
/**
 * 遍历后台传来的路由，转换为组件对象
 * @param asyncRouterMap  路由tree
 * @param lastRouter  上一次的路由
 * @returns {*}
 */
function filterAsyncRouter(asyncRouterMap, lastRouter = null) {
  //处理菜单
  return asyncRouterMap.filter(route => {

    // route.name = route.name
    route.meta = {
      title: route.title,
      auth: true,
      icon: route.icon,
      cache: route.isCache === 1,
      roles: [],
      hidden:route.status === 1
    }
    //处理目录
    if (route.type === 1) {
      route.component = layoutHeaderAside
      //判断是否有子级，并且子级所有的的hidden为false
      if (route.children && route.children.length) {
       let arr= route.children.filter(i=>i.status===0)
        if (!arr.length) {
          route.meta.hidden = true
        }
      }
      //  处理页面
    } else if (route.type === 2) {
      //这里有个问题如果他没有父级我需要给一个假的父级,还要保证在下面不会进入循环
      if (!lastRouter) {
        route.component = layoutHeaderAside
        //让这个对象先和原本的对象丢失关系
        const cloneRoute = cloneDeep(route)
        //clone一份原本的children
        let cloneChildren = []
        if (cloneRoute.children) {
          cloneChildren = cloneDeep(cloneRoute.children)
        }
        //重新把他当作1级处理
        route.type = 1
        route.children = [
          {
            ...route,
            children: cloneChildren,
            type: 2,
          },
        ]
      } else {
        route.component = loadView(route.path)
      }

      //  处理按钮
    } else if (route.type === 3) {
     try {
       lastRouter.meta.roles.push(route.perm)
     }catch (e) {

     }
    }

    if (route.children != null && route.children && route.children.length) {
      //  在这里处理
      if (route.type === 2) {
        route.children1 = route.children
        delete route.children
        route.children1 = filterAsyncRouter(route.children1, route)
      } else {
        route.children = filterAsyncRouter(route.children, route)
      }
    } else {
      delete route['children']
    }
    return true
  })
}

/**
 *动态渲染路由
 * @param list{Array} //路由表
 */
function addRoute(list) {
  if (list && list[0]) {
    let isErr = false
    list.forEach(i => {
      let Err = null
      try {
        router.addRoute(i)
      } catch (e) {
        Err = e
        isErr = true
      }
      if (isErr) {
        console.log('错误组件', i)
        throw new Error(Err)
      }
    })
  }

}

export const filterRoute = filterAsyncRouter
export const addRoutes = addRoute
